<?php

namespace App\Http\Controllers\Open;

use App\Facades\ClientAuth;
use App\Facades\Option;
use App\Http\Controllers\Controller;
use App\Models\Menu;
use App\Services\Spider\WuzhuisoDrive;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use mysql_xdevapi\Exception;
use Overtrue\LaravelWeChat\Facade as EasyWeChat;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;


/*
 * 2023.10。14
 * 将集合的数据同步到xunyua
 */
class XgController extends Controller
{

    /*

     */
    public function index(){
        echo 'xg路由成功!!!!!!';
        die;
    }

    public function show() {
        echo 'show!!!';
        die;
    }
    
    public function test() {
        $keylists = DB::table('xg_searchkeyword')->where(['status'=>0])->select()->get()->toArray(); //`status` 0表示有效，-1表示删除，1表示已经用过',
        $keywordInfo =  $keylists[0];
        echo "\r\n site_id : {$keywordInfo->site_id}; searchkeyword : {$keywordInfo->searchkeyword} >>>> ";
        $ret = self::spider($keywordInfo);
        if ($ret>0) {
            DB::table('xg_searchkeyword')->where(['id'=>$keywordInfo->id])->update(['status'=>$ret,'created_time'=>date("Y-m-d H:i:s")]);
            if ($ret!=1) {
                save_log([
                    'site_id'=>$keywordInfo->site_id,
                    'site_id'=>$keywordInfo->searchkeyword,
                    'msg'=>'抓取空内容'
                ],'spider');
            }
        }

    }


    private static function spider($keywordInfo) {
        if (!$keywordInfo) return -1;
        $table = 'xg_spider_'.$keywordInfo->site_id;
        self::createSchema($table);
        $keywordInfo->searchkeyword="证券公司开户";
        $spiderInfo = self::__spider($keywordInfo->searchkeyword);
        if (!$spiderInfo) {
            return 2;  //抓取失败，内容为空
        }
        DB::table($table)->insert([
            'site_id'=>$keywordInfo->site_id,
            'keyword_id'=>$keywordInfo->id,
            'title'=>$spiderInfo['title'],
            'content' =>  htmlspecialchars($spiderInfo['article'], ENT_QUOTES, 'UTF-8'),
            'created_at'=>date("Y-m-d H:i:s"),
            'updated_at'=>date("Y-m-d H:i:s")
        ]);
        return 1;
    }


    private static function createSchema($tabname) {
        if (!$tabname) {
            throw new \Exception('判断的表名不能为空');
        }
        if (!Schema::hasTable($tabname)) {
            // 如果表不存在,则创建表
            Schema::create($tabname, function (Blueprint $table) {
                $table->bigIncrements('id'); // 使用 bigIncrements 方法设置 id 为自增主键
                $table->integer('site_id')->default(0)->required();;
                $table->integer('keyword_id')->default(0)->required();;
                $table->text('title')->required();
                $table->text('content')->required();
                $table->integer('is_delete')->default(0);
                $table->timestamps(); // 添加时间戳
            });
        }
    }

    private static function __spider($keyword) {
        //$siteLists = DB::table('xg_site')->where(['is_stop'=>0])->select()->get()->toArray();

        $wuzhuisoDrive = new WuzhuisoDrive();
        $spider =  $wuzhuisoDrive->claws($keyword);
        if (!$spider || !$spider['lists']) {
            return false;
        }

        $articles = [];
        foreach($spider['lists'] as $k2=>$v2) {
            if ($v2['title'] && $v2['short_article']) {
                $articles[] = "<div class='sdw2_title sub_title'>".$v2['title']."</div>";
                $articles[] =  "<div class='sdw2_article sub_article'>".$v2['short_article']."</div>";
            }
        }
        if (count($articles)==0) {
            return false;
        }
        return ['title'=>$spider['lists'][0]['title'],'article'=>implode("",$articles)];

    }


}
